package com.wuax.filter;

import com.wuax.domain.vo.Result;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 重复登录拦截器
 */
public class NoRepeatLogin implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取当前session，判断有没有用户，有的话就是重复登录了
        HttpServletRequest hrequest = (HttpServletRequest) request;
        HttpServletResponse hresponse = (HttpServletResponse) response;
        HttpSession session = hrequest.getSession(false);
        if (session != null && (session.getAttribute("sys_user") != null)) {
            hresponse.setContentType("text/json; charset=UTF-8");
            Result error = Result.error("重复登录");
            hresponse.getWriter().write(error.toJson());
        } else {
            chain.doFilter(hrequest, hresponse);
        }
    }

    public void destroy() {
        // TODO Auto-generated method stub
    }

    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
